<template>
    <h3>基本信息</h3>
    <ContentWrap>
        <el-table :data="stuDetails">
            <el-table-column label="学生学号" prop="code" min-width="120"/>
            <el-table-column label="名称" prop="name" min-width="100"/>
            <el-table-column label="头像" prop="avatar" width="50">
                <template #default="scope">
                    <div style="width: 36px; height: 36px">
                        <el-image v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"
                                  preview-teleported hide-on-click-modal/>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="手机号" prop="mobile" min-width="120"/>
            <el-table-column label="归属学校" prop="schoolName"/>
            <el-table-column label="当前年级" prop="grade">
                <template #default="scope">
                    {{ getTermLabel(scope.row.grade, scope.row.term) }}
                </template>
            </el-table-column>
            <el-table-column label="班级" prop="className"/>
            <el-table-column label="专业" prop="majors" min-width="200">
                <template #default="scope">
                    <el-tag v-for="tag in scope.row.majors" type="warning" :key="tag"
                            :disable-transitions="true" class="mr-5px">
                        {{ tag.name }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="乐器" prop="musical" min-width="200"/>
            <el-table-column label="类型" prop="type">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.YXT_USER_TYPE" :value="scope.row.type"/>
                </template>
            </el-table-column>
            <el-table-column label="性别" prop="sex">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex"/>
                </template>
            </el-table-column>
            <el-table-column label="预约权限" prop="canSub">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.canSub"/>
                </template>
            </el-table-column>
        </el-table>
    </ContentWrap>

    <h3>课程信息</h3>
    <ContentWrap>
        <el-form class="-mb-15px" :model="queryCourseParams" ref="queryCourseFormRef" :inline="true" label-width="68px">
            <el-form-item label="年级" prop="grade">
                <el-select v-model="queryCourseParams.grade" placeholder="请选择年级" clearable>
                    <el-option v-for="item in grades" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="学期" prop="term">
                <el-select v-model="queryCourseParams.term" placeholder="请选择学期" clearable>
                    <el-option v-for="item in terms" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleCouQuery">
                    <Icon icon="ep:search" class="mr-5px"/>
                    搜索
                </el-button>
                <el-button @click="resetCouQuery">
                    <Icon icon="ep:refresh" class="mr-5px"/>
                    重置
                </el-button>
                <el-button
                    type="success"
                    plain
                    @click="handleCouExport"
                    :loading="exportCouLoading"
                    v-hasPermi="['yxt:member:export']"
                >
                    <Icon icon="ep:download" class="mr-5px"/>
                    导出
                </el-button>
            </el-form-item>
        </el-form>
    </ContentWrap>

    <el-descriptions class="margin-top" title="上课总数" :column="2" border>
        <el-descriptions-item>
            <template #label>
                本学期上课总数
            </template>
            {{ couCount }} 节
        </el-descriptions-item>
    </el-descriptions>

    <!-- 上课列表 -->
    <ContentWrap>
        <el-table v-loading="couLoading" :data="courseList" @selection-change="handleCouSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="学生姓名" align="center" prop="memberName"/>
            <el-table-column label="授课教师" align="center" prop="teacherName"/>
            <el-table-column label="专业" align="center" prop="majorName"/>
            <el-table-column label="上课次数" align="center" prop="courseCount"/>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button link type="primary" @click="openDeatilForm(scope.row)">
                        查看
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <Pagination :total="couTotal"
                    v-model:page="queryCourseParams.pageNo"
                    v-model:limit="queryCourseParams.pageSize"
                    @pagination="getCouList"/>
    </ContentWrap>

    <el-dialog title="教师课程详情" v-model="dialogFormVisible" draggable destroy-on-close>
        <el-table :data="courseDetalList" height="360px">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="授课教师" prop="name"/>
            <el-table-column label="专业" prop="majorName"/>
            <el-table-column label="上课时间" :formatter="dateFormatter" prop="startTime" width="180"/>
            <el-table-column label="课后总结" prop="summary"/>
            <el-table-column label="课后总结图片" prop="picture">
                <template #default="scope">
                    <div style="width: 36px; height: 36px">
                        <el-image v-if="scope.row.picture" :src="scope.row.picture"
                                  :preview-src-list="[scope.row.picture]" preview-teleported hide-on-click-modal/>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
    <span class="dialog-footer">
      <el-button type="primary" @click="closeDialog">确 定</el-button>
    </span>
        </template>
    </el-dialog>

    <h3>练琴信息</h3>

    <!--练琴列表-->
    <ContentWrap>
        <el-form
            class="-mb-15px"
            :model="querySubParams"
            ref="querySubFormRef"
            :inline="true"
            label-width="68px"
        >
            <el-form-item label="年级" prop="grade">
                <el-select v-model="querySubParams.grade" placeholder="请选择年级" clearable>
                    <el-option v-for="item in grades" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="学期" prop="term">
                <el-select v-model="querySubParams.term" placeholder="请选择学期" clearable>
                    <el-option v-for="item in terms" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="querySubParams.status" placeholder="请选择状态" clearable>
                    <el-option v-for="item in statusList" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleSubQuery">
                    <Icon icon="ep:search" class="mr-5px"/>
                    搜索
                </el-button>
                <el-button @click="resetSubQuery">
                    <Icon icon="ep:refresh" class="mr-5px"/>
                    重置
                </el-button>
                <el-button
                    type="success"
                    plain
                    @click="handleSubExport"
                >
                    <Icon icon="ep:download" class="mr-5px"/>
                    导出
                </el-button>
            </el-form-item>
        </el-form>
    </ContentWrap>


    <el-descriptions class="margin-top"
                     title="练琴信息"
                     :column="3"
                     border
    >
        <el-descriptions-item>
            <template #label>
                本学期总练琴时长
            </template>
            {{ duration }}
        </el-descriptions-item>
        <el-descriptions-item>
            <template #label>
                本学期爽约次数
            </template>
            {{ brokenCount }}
        </el-descriptions-item>
        <el-descriptions-item>
            <template #label>
                本学期取消次数
            </template>
            {{ cancelCount }}
        </el-descriptions-item>
    </el-descriptions>
    <ContentWrap>
        <el-table v-loading="subLoading" :data="subList" @selection-change="handleSubSelectionChange">\
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="学生姓名" align="center" prop="memberName"/>
            <el-table-column label="教学楼" align="center" prop="buildingName"/>
            <el-table-column label="楼层" align="center" prop="floor"/>
            <el-table-column label="琴房号" align="center" prop="number"/>
            <el-table-column :formatter="dateFormatter" label="开始时间" align="center" prop="startTime"/>
            <el-table-column label="预约时长" align="center" prop="keepTime"/>
            <el-table-column label="实际时长" align="center" prop="actualTime"/>
            <el-table-column label="预约状态" align="center" prop="status">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.YXT_SUBSCRIBE_STATUS" :value="scope.row.status"/>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
            :total="subTotal"
            v-model:page="querySubParams.pageNo"
            v-model:limit="querySubParams.pageSize"
            @pagination="getSubList"
        />
    </ContentWrap>
</template>
<script lang="ts" setup>
import * as MemberApi from "@/api/yxt/member";
import {useCourseApi, useCourseDetailApi} from "@/api/yxt/course";
import {DICT_TYPE} from "@/utils/dict";
import {useSubscribeApi} from "@/api/yxt/subscribe";
import {useConfirm} from "@/components/Notice";
import {dateFormatter} from "@/utils/formatTime";
import * as XLSX from 'xlsx';

defineOptions({name: 'YxtStuDetail'})

const {t} = useI18n() // 国际化
const route = useRoute() // 路由

const couLoading = ref(true) // 列表的加载中
const subLoading = ref(true)
const couTotal = ref(0) // 列表的总页数
const subTotal = ref(0) //预约总数量
const queryCourseParams = reactive({
    pageNo: 1,
    pageSize: 10,
    grade: undefined,
    term: undefined,
    memberId: route.params.stuId
})
const querySubParams = reactive({
    pageNo: 1,
    pageSize: 10,
    grade: undefined,
    term: undefined,
    status: undefined,
    memberId: route.params.stuId
})
const queryCourseFormRef = ref() // 搜索的表单
const querySubFormRef = ref() // 搜索的表单
const exportCouLoading = ref<boolean>(false) // 导出的加载中
const stuDetails = ref<Array<any>>([]) //学生详细信息
const courseList = ref<Array<any>>([]) //课程详情列表
const subList = ref<Array<any>>([]) //练琴详情列表

const multipleSubSelection = ref<Array<any>>([])
const multipleCouSelection = ref<Array<any>>([])
const handleCouSelectionChange = (val) => {
    multipleCouSelection.value = val;
}
const handleSubSelectionChange = (val) => {
    multipleSubSelection.value = val;
}

const grades = ref([
    {name: "大一", id: 1},
    {name: "大二", id: 2},
    {name: "大三", id: 3},
    {name: "大四", id: 4}
])
const terms = ref([
    {name: "上学期", id: 1},
    {name: "下学期", id: 2},
])
const statusList = ref([
    {id: 1, name: "未开始"},
    {id: 2, name: "待签到"},
    {id: 3, name: "进行中"},
    {id: 4, name: "已完成"},
    {id: 5, name: "已取消"},
    {id: 6, name: "爽约"},
])
const dialogFormVisible = ref(false)
const courseDetalList = ref<Array<any>>([])
const couCount = ref<number>(0)
const duration = ref<number>(0)
const cancelCount = ref<number>(0)
const brokenCount = ref<number>(0)

const openDeatilForm = async (rowData: any) => {
    dialogFormVisible.value = true
    courseDetalList.value = await useCourseApi().courseListForStu({
        majorId: rowData.majorId,
        teaId: rowData.teacherId,
        stuId: rowData.memberId
    })
}

const closeDialog = () => {
    dialogFormVisible.value = false
}

/** 查询列表 */
const getCouList = async () => {
    couLoading.value = true
    try {
        const data = await useCourseDetailApi().getList(queryCourseParams)
        courseList.value = data.result.list
        couTotal.value = data.result.total
        couCount.value = data.couCount
    } finally {
        couLoading.value = false
    }
}

const getSubList = async () => {
    subLoading.value = true
    try {
        const data = await useSubscribeApi().subListForMem(querySubParams)
        subList.value = data.subList.list
        subTotal.value = data.subList.total
        duration.value = data.duration
        cancelCount.value = data.cancelCount
        brokenCount.value = data.brokenCount
    } finally {
        subLoading.value = false
    }
}

/** 搜索按钮操作 */
const handleCouQuery = () => {
    queryCourseParams.pageNo = 1
    getCouList()
}

/** 搜索按钮操作 */
const handleSubQuery = () => {
    querySubParams.pageNo = 1
    getSubList()
}
/** 重置按钮操作 */
const resetCouQuery = () => {
    queryCourseFormRef.value.resetFields()
    handleCouQuery()
}

/** 重置按钮操作 */
const resetSubQuery = () => {
    querySubFormRef.value.resetFields()
    handleSubQuery()
}

/** 导出按钮操作 */
const handleCouExport = async () => {
    useConfirm(t("common.exportMessage"), async () => {
        exportCouLoading.value = true
        try {
            if (courseList.value.length == 0) {
                useMessage().warning("没有可导出数据")
                return;
            }
            const exportData = multipleCouSelection.value.length > 0 ? multipleCouSelection.value
                : await useCourseDetailApi().getListNoPage(queryCourseParams);
            const formatData = exportData.map(formatCouData);
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(formatData);
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "选中数据");

            // 生成文件
            XLSX.writeFile(wb, "课程数据.xlsx");
        } finally {
            exportCouLoading.value = false
        }
    });
}

const formatCouData = (item: any) => {
    return {
        "学生姓名": item.memberName,
        "授课教师": item.teacherName,
        "专业": item.majorName,
        "上课次数": item.courseCount
    }
}

/** 导出按钮操作 */
const handleSubExport = async () => {
    useConfirm(t("common.exportMessage"), async () => {
        exportCouLoading.value = true
        try {
            if (subList.value.length == 0) {
                useMessage().warning("没有可导出数据")
                return;
            }
            const exportData = multipleSubSelection.value.length > 0 ? multipleSubSelection.value
                : await useSubscribeApi().subListForMemNoPage(querySubParams);
            const formatData = exportData.map(formatSubData)
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(formatData);
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "选中数据");

            // 生成文件
            XLSX.writeFile(wb, "预约数据.xlsx");
        } finally {
            exportCouLoading.value = false
        }
    });
}

const formatSubData = (item: any) => {
    return {
        "学生姓名": item.memberName,
        "教学楼": item.buildingName,
        "楼层": item.floor,
        "琴房号": item.number,
        "开始时间": formatDateTime(item.startTime),
        "预约时长": item.keepTime,
        "实际时长": item.actualTime,
        "预约状态": getSubStatus(item.status)
    }
}

//时间戳格式化为时间
const formatDateTime = (timestamp: any) => {
    const formattedDate = new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false, // 使用 24 小时制
    }).format(new Date(timestamp));
    return formattedDate;
}

const getSubStatus = (status: any) => {
    let subStatus = '';
    switch (status) {
        case 1:
            subStatus = '未开始';
            break;
        case 2:
            subStatus = '待签到';
            break;
        case 3:
            subStatus = '进行中';
            break;
        case 4:
            subStatus = '已完成';
            break;
        case 5:
            subStatus = '已取消';
            break;
        case 6:
            subStatus = '爽约';
            break;
        default:
            subStatus = '未知';
    }
    return subStatus;
}


/**
 * 基本信息
 */
const getStuDetail = async () => {
    const stuDetail = await MemberApi.useMemberApi().getMember(queryCourseParams.memberId)
    stuDetails.value.push(stuDetail);
}

/**
 * 年级
 */
function getTermLabel(grade, term) {
    // 根据 grade 和 term 生成学期标签
    let gradeLabel = '';
    switch (grade) {
        case 1:
            gradeLabel = '大一';
            break;
        case 2:
            gradeLabel = '大二';
            break;
        case 3:
            gradeLabel = '大三';
            break;
        case 4:
            gradeLabel = '大四';
            break;
        case 5:
            gradeLabel = '已毕业';
            break;
        default:
            gradeLabel = '已毕业';
    }
    if (grade == 5) return gradeLabel;
    let termLabel = '';
    switch (term) {
        case 1:
            termLabel = '(上)';
            break;
        case 2:
            termLabel = '(下)';
            break;
        default:
            termLabel = '';
    }
    return gradeLabel + termLabel;
}

/** 初始化 **/
onMounted(async () => {
    await getStuDetail()
    await getCouList()
    await getSubList()
})
</script>
